<?php

class database
{
    static private $instance = null;
    
	protected $error_num = 0;	// 错误代码
	protected $error_msg = '';	// 错误信息
	
	protected $connection = null;	// 数据库连接
	protected $cursor = null;	    // 查询结果游标
	
	
	// 构造函数 私有， 单件模式, 禁止用户创建实例
	private function __construct()
	{
		$config = bone::get_config('db');

		if (!function_exists('mysql_connect'))
		{
			$this->error_num = 1;
			$this->error_msg = 'MySql函数不可用';
			return false;
		}

		if (!($this->connection = mysql_connect($config->db_host, $config->db_user, $config->db_pass, true)))
		{
			$this->error_num = 2;
			$this->error_msg = '连接 MySQL 失败';
			return false;
		}

		if (!mysql_select_db($config->db_name, $this->connection))
		{
			$this->error_num = 3;
			$this->error_msg = '登陆成功, 数据库 '.$config->db_name.' 不存在';
			return false;
		}

		mysql_query( "SET NAMES 'utf8'", $this->connection );
	}

		
	// 析构函数
	public function __destruct()
	{
	    self::$instance = null;
		if (is_resource($this->connection))
		{
			mysql_close($this->connection);
		}		
	}
	
	
	// 防止克隆
	private function __clone(){}
	
	
    // 获取数据库实例
	static function &get_instance()
	{
	    if(self::$instance==null)
	    {
	        self::$instance = new database();
	    }
	    return self::$instance;
	}
	
	
	//  执行 sql 语句
	public function execute( $sql, $offset = 0, $limit = 0 )
	{
		if (!is_resource($this->connection))
		{
			return false;
		}

		if ($offset > 0 || $limit > 0)
		{
			$sql .= ' LIMIT '.$offset.', '.$limit;
		}

		$this->error_num = 0;
		$this->error_msg = '';
		$this->cursor = mysql_query($sql, $this->connection);

		if (!$this->cursor)
		{
			$this->error_num = mysql_errno($this->connection);
			$this->error_msg = mysql_error($this->connection)." SQL=$sql";
			return false;
		}
		return $this->cursor;
	}


	// 返回单一查询结果, 多行多列记录时, 只返回第一行第一列 
	public function get_result( $sql )
	{
		if (!($cursor = $this->execute( $sql,0,1 )))
		{
			return null;
		}
		$data = null;
		if ($row = mysql_fetch_row($cursor))
		{
			$data = $row[0];
		}
		mysql_free_result($cursor);
		return $data;
	}


	// 返回一个对象
	public function get_object( $sql )
	{
		if (!($cursor = $this->execute( $sql,0,1 )))
		{
			return null;
		}
		$data = null;
		if ($obj = mysql_fetch_object($cursor))
		{
			$data = $obj;
		}
		mysql_free_result($cursor);
		return $data;
	}

	// 返回一个对象数组，如果设置了 $key, 该数组按该 key 生成索引下标。
	public function get_objects( $sql, $offset = 0, $limit = 0, $key='')
	{
		if (!($cursor = $this->execute( $sql, $offset, $limit )))
		{
			return null;
		}
		$datas = array();
		while ($row = mysql_fetch_object($cursor))
		{
			if ($key)
			{
				$datas[$row->$key] = $row;
			}
			else
			{
				$datas[] = $row;
			}
		}
		mysql_free_result($cursor);
		return $datas;
	}


	// 插入一个对象到数据库
	public function insert_object($table, &$object)
	{
		$fields = array();
		$values = array();
		foreach (get_object_vars($object) as $key => $value)
		{
			if (is_array($value) || is_object($value) || $value === NULL)
			{
				continue;
			}

			$fields[] = '`'.$key.'`';
			$values[] = '\''.$value.'\'';
		}

		$sql = 'INSERT INTO `'.$table.'` ('.implode(',', $fields).') VALUES ('.implode(',', $values).') ';
		if (!$this->execute( $sql ))
		{
			return false;
		}

		return true;
	}


	// 更新一个对象到数据库
	public function update_object($table, &$object, $key_name, $update_null=true)
	{
		$datas = array();
		$where = null;
		foreach (get_object_vars($object) as $key => $value)
		{
			if (is_array($value) || is_object($value) )
			{
				continue;
			}

			// 主健不更新
			if ($key == $key_name)
			{
				$where = '`'.$key_name.'`=\''. $value.'\'';
				continue;
			}
			if ($value === null)
			{
				if ($update_null)
				{
					$value = 'NULL';
				}
				else 
				{
					continue;
				}
			}
			else 
			{
				$value = '\''. $value.'\'';
			}
			$datas[] = '`'.$key.'`='.$value;
		}
		$sql = 'UPDATE `'.$table.'` SET '.implode(",", $datas);
		if($where)
		{
			$sql .= ' WHERE '.$where;
		}

		return $this->execute( $sql );
	}


	// 获取 insert 插入后产生的 id
	public function get_insert_id()
	{
		return mysql_insert_id($this->connection);
	}

	// 获取所有表名
	public function get_tables()
	{
		return $this->get_objects( 'SHOW TABLES' );
	}

	// 获取一个表的字段列表
	public function get_table_fields($table)
	{
		$fields = $this->get_objects( 'SHOW FIELDS FROM ' . $table );
		
		$datas = array();
		foreach ($fields as $field) {
			$datas[$field->Field] = $field;
		}
		return $datas;
	}
	
	

	// 获取错误编号
	public function get_error_num()
	{
		return $this->error_num;
	}

	// 获取错误信息
	public function get_error_msg()
	{
		return $this->error_msg;
	}


	// 获取版本号
	public function get_version()
	{
		return mysql_get_server_info($this->connection);
	}


}
